from flask import Blueprint, render_template, redirect, url_for, flash, request
from flask_login import login_required, current_user
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime

from app import db
from app.models.user import User
from app.models.order import Order

user = Blueprint('user', __name__, url_prefix='/user')

@user.route('/list')
@login_required
def list():
    """用户列表"""
    # 获取筛选参数
    username = request.args.get('username', '')
    email = request.args.get('email', '')
    phone = request.args.get('phone', '')
    is_admin = request.args.get('is_admin', '')
    
    # 构建查询
    query = User.query
    
    # 应用筛选条件
    if username:
        query = query.filter(User.username.like(f'%{username}%'))
    if email:
        query = query.filter(User.email.like(f'%{email}%'))
    if phone:
        query = query.filter(User.phone.like(f'%{phone}%'))
    if is_admin != '':
        query = query.filter(User.is_admin == (is_admin == '1'))
    
    users = query.all()
    return render_template('user/list.html', users=users)

@user.route('/detail/<int:user_id>')
@login_required
def detail(user_id):
    """用户详情"""
    user_info = User.query.get_or_404(user_id)
    # 查询用户订单
    orders = Order.query.filter_by(user_id=user_id).all()
    return render_template('user/detail.html', user=user_info, orders=orders)

@user.route('/add', methods=['GET', 'POST'])
@login_required
def add():
    """添加用户"""
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        confirm_password = request.form.get('confirm_password')
        email = request.form.get('email', '')
        phone = request.form.get('phone', '')
        is_admin = bool(request.form.get('is_admin'))
        
        # 简单验证
        if not username or not password:
            flash('用户名和密码不能为空!', 'danger')
            return render_template('user/form.html', user=None)
        
        if password != confirm_password:
            flash('两次输入的密码不一致!', 'danger')
            return render_template('user/form.html', user=None)
        
        # 检查用户名是否已存在
        if User.query.filter_by(username=username).first():
            flash('用户名已存在!', 'danger')
            return render_template('user/form.html', user=None)
        
        # 创建新用户 - 使用明文密码
        new_user = User(
            username=username,
            password=password,  # 直接存储明文密码
            email=email,
            phone=phone,
            is_admin=is_admin,
            create_time=datetime.now()
        )
        
        db.session.add(new_user)
        db.session.commit()
        
        flash('用户创建成功!', 'success')
        return redirect(url_for('user.list'))
    
    return render_template('user/form.html', user=None)

@user.route('/edit/<int:user_id>', methods=['GET', 'POST'])
@login_required
def edit(user_id):
    """编辑用户"""
    user_info = User.query.get_or_404(user_id)
    
    if request.method == 'POST':
        user_info.username = request.form.get('username')
        user_info.email = request.form.get('email', '')
        user_info.phone = request.form.get('phone', '')
        user_info.is_admin = bool(request.form.get('is_admin'))
        
        # 可以添加更多字段的更新
        
        db.session.commit()
        
        flash('用户信息更新成功!', 'success')
        return redirect(url_for('user.detail', user_id=user_id))
    
    return render_template('user/form.html', user=user_info)

@user.route('/toggle_status/<int:user_id>')
@login_required
def toggle_status(user_id):
    """
    由于数据库没有status字段，此功能暂不可用
    """
    flash('该功能暂不可用：数据库不支持禁用用户操作', 'warning')
    return redirect(url_for('user.detail', user_id=user_id))

@user.route('/delete/<int:user_id>')
@login_required
def delete(user_id):
    """删除用户"""
    user_info = User.query.get_or_404(user_id)
    
    # 不允许删除自己
    if user_info.user_id == current_user.user_id:
        flash('不能删除当前登录用户!', 'danger')
        return redirect(url_for('user.detail', user_id=user_id))
    
    db.session.delete(user_info)
    db.session.commit()
    
    flash('用户已删除!', 'success')
    return redirect(url_for('user.list'))

@user.route('/profile')
@login_required
def profile():
    """当前用户个人资料"""
    return render_template('user/profile.html', user=current_user)

@user.route('/update_profile', methods=['POST'])
@login_required
def update_profile():
    """更新个人资料"""
    email = request.form.get('email')
    phone = request.form.get('phone')
    current_password = request.form.get('current_password')
    new_password = request.form.get('new_password')
    
    # 更新基本信息
    current_user.email = email
    current_user.phone = phone
    
    # 如果要更改密码
    if current_password and new_password:
        # 直接比较明文密码
        if current_user.password == current_password:
            # 更新密码 - 直接设置明文密码
            current_user.password = new_password
            flash('密码已更新!', 'success')
        else:
            flash('当前密码不正确!', 'danger')
            return redirect(url_for('user.profile'))
    
    db.session.commit()
    
    flash('个人资料已更新!', 'success')
    return redirect(url_for('user.profile')) 